package com.dragon.utilslibrary.tools;

import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.UUID;

public class ToolUtils {



    public static byte[] longToByteArray1(long i) {
        byte[] result = new byte[4];
        result[0] = (byte) ((i >> 24) & 0xFF);
        result[1] = (byte) ((i >> 16) & 0xFF);
        result[2] = (byte) ((i >> 8) & 0xFF);
        result[3] = (byte) (i & 0xFF);
        return result;
    }

    public static byte[] getRandom(){
        byte[] data = new byte[16];
        for (int i = 0; i < 16; i++){
            data[i] = (byte) (new Random().nextInt(255) + 1);
        }
        return data;
    }

    public static byte[] intToByte(int i){
        byte[] result = new byte[2];
        result[0] = (byte) ((i >> 8) & 0xFF);
        result[1] = (byte) (i & 0xFF);
        return result;
    }

    /**
     * 大端在后
     * @param i
     * @return byte[]
     */
    public static byte[] intToByte1(int i){
        byte[] result = new byte[2];
        result[1] = (byte) ((i >> 8) & 0xFF);
        result[0] = (byte) (i & 0xFF);
        return result;
    }

    public static byte[] getRandomData(int mtu){
        if (mtu > 5){
            byte[] data = new byte[mtu - 5];
            for (int i = 0; i < mtu -5; i++){
                data[i] = (byte) i;
            }
            return data;
        } else {
            return new byte[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0f, 0x10, 0x11, 0x12};
        }
    }


    /**
     * ascii字符转16进制字符
     * @param str ascii字符
     * @return String
     */
    public static String convertStringToHex(String str){

        char[] chars = str.toCharArray();

        StringBuffer hex = new StringBuffer();
        for(int i = 0; i < chars.length; i++){
            hex.append(Integer.toHexString((int)chars[i]));
        }

        return hex.toString();
    }

    /***
     * 获取本地时间相对于utc标准时间的偏移量
     * @return byte[]
     */
    public static byte[] getTimeZone(){
        byte[] timeData = new byte[2];
        Date date = new Date();
        date.setTime(System.currentTimeMillis());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int rawOffset = calendar.get(Calendar.ZONE_OFFSET);//时区偏移，毫秒级
        int dstOffset = calendar.get(Calendar.DST_OFFSET);//是否为夏令时0||3600000
        int timeOffset = (rawOffset + dstOffset)/1000;//时间偏移，秒级
        if (timeOffset < 0){
            timeData[0] = (byte) (0x80 + Math.abs(timeOffset)/3600);
            timeData[1] = (byte) (Math.abs(timeOffset)%3600/60);
        } else {
            timeData[0] = (byte) (Math.abs(timeOffset)/3600);
            timeData[1] = (byte) (Math.abs(timeOffset)%3600/60);
        }
        return timeData;
    }

//    public static byte[] getUserTimeZone(){
//        byte[] data = new byte[2];
//        String timeZone = TimeZone.getDefault().getDisplayName(false, TimeZone.SHORT);
//        String[] split = timeZone.split(":");
//        if (split != null && split.length == 2) {
//            String s = split[0];
//            if (s != null && !s.equals("") && s.length() > 3) {
//                String[] split1 = s.split("");
//                if (split1 != null) {
//                    String mark = split1[split1.length - 3];
//                    String h_str = split1[split1.length - 2] + split1[split1.length - 1];
//                    int h = Integer.parseInt(h_str);
//                    String min_str = split[1];
//                    int min = Integer.parseInt(min_str);
//                    if (!TextUtils.isEmpty(mark)) {
//                        if (mark.equals("+")) {
//                            data[0] = (byte) h;
//                            data[1] = (byte) min;
//                        } else {
//                            data[0] = (byte) (h + 0x80);
//                            data[1] = (byte) min;
//                        }
//                    }
//                }
//            }
//        }
//        return data;
//    }

    public static String byteArrayToHexString1(byte[] bytes) {
        if (null != bytes) {
            StringBuilder sb = new StringBuilder(bytes.length * 2);
            for (int i = 0; i <= bytes.length - 1; i++) {
                if ((bytes[i] & 0xff) < 0x10) {
                    sb.append('0');
                }
                sb.append(Integer.toHexString(0xff & bytes[i]));
            }
            return sb.toString();
        } else {
            LogUtils.i("ToolUtils", "null == bytes");
        }

        return null;
    }

    /**
     * 反向输出16进制字符
     * @param bytes byte[]
     * @return String
     */
    public static String byteArrayToHexString(byte[] bytes) {
        if (null != bytes) {
            StringBuilder sb = new StringBuilder(bytes.length * 2);
            for (int i = bytes.length - 1; i >= 0; i--) {
                if ((bytes[i] & 0xff) < 0x10) {
                    sb.append('0');
                }
                sb.append(Integer.toHexString(0xff & bytes[i]));
            }
            return sb.toString();
        } else {
            LogUtils.i("ToolUtils", "null == bytes");
        }

        return null;
    }

    public static String byteToHexString(byte data){
        StringBuilder sb = new StringBuilder(2);
        if ((data&0xff) < 0x10){
            sb.append('0');
        }
        sb.append(Integer.toHexString(0xff & data));
        return sb.toString();
    }

    /**
     * 获取TLV中可变字节的L值，其中bit7为1表示后面还有一个byte，为0表示length到此结束
     * @param length 1byte 0-127,2byte 128-16383
     * @return TLV中L的值
     */
    public static byte[] getLengthByte(int length){
        if (length <= 127){
            return new byte[]{(byte) length};
        } else {
            return ConvertUtils.byte2ArraySet(new byte[]{(byte) (length/128 + 128)}, new byte[]{(byte) (length%128)});
        }
    }

    /**
     * 时间转配速
     * @param time 时间
     * @return 配速
     */
    public static String timeToPace(int time) {
        DecimalFormat dfDecimalFormat = new DecimalFormat("00", new DecimalFormatSymbols(Locale.US));
        int minute = time / 60;
        String second = dfDecimalFormat.format(time%60);
        return minute + "′" + second + "″";
    }

    /**
     * 配速转速度
     * @param pace 配速
     * @return 速度
     */
    public static String paceToSpeed(int pace) {
        DecimalFormat dfDecimalFormat = new DecimalFormat("0.00", new DecimalFormatSymbols(Locale.US));
        float speeds = 3600*1.0f / pace;
        String speed = dfDecimalFormat.format(speeds);
        return speed;
    }

    /**
     * 配速转速度英制
     * @param pace 配速
     * @return 速度
     */
    public static String paceToSpeedMile(int pace) {
        DecimalFormat dfDecimalFormat = new DecimalFormat("0.00", new DecimalFormatSymbols(Locale.US));
        float speeds = 3600 * 0.6213712f / pace;
        String speed = dfDecimalFormat.format(speeds);
        return speed;
    }

    /**
     * 把byte加到list里，注意，必须要按顺序加
     * @param list
     * @param bytes
     * @return
     */
    public static ArrayList<Byte> addBytes(ArrayList<Byte> list, byte[] bytes){
        if(list != null && bytes !=null && bytes.length > 0){
            for (byte b:bytes) {
                list.add(b);
            }
        }
        return list;
    }

    /**
     * 使用for循环
     * @param list
     * 将被转换为byte[]的List<Byte>
     * @return
     * 转换成的byte数组
     */
    public static byte[] listTobyte(List<Byte> list) {
        if (list == null || list.size() < 0)
            return null;
        byte[] bytes = new byte[list.size()];
        int i = 0;
        Iterator<Byte> iterator = list.iterator();
        while (iterator.hasNext()) {
            bytes[i] = iterator.next();
            i++;
        }
        return bytes;
    }

    public static byte[] shortToByteArray(short number) {
        byte[] arr = new byte[2];
        arr[0] = (byte) ((number >> 8) & 0xff);
        arr[1] = (byte) (number & 0xff);

        return arr;
    }

    /**
     * 4byte数据转无符号long
     * @param data1 第一个byte
     * @param data2 第二个byte
     * @param data3 第三个byte
     * @param data4 第四个byte
     * @return long
     */
    public static long byteToLong(byte data1, byte data2, byte data3, byte data4) {
        long num = (((long) (data1 & 0xff)) << 24) + ((data2 & 0xff) << 16) + ((data3 & 0xff) << 8) + (data4 & 0xff);
        return num;
    }

    /**
     * 4byte数据转有符号int
     * @param data1 第一个byte
     * @param data2 第二个byte
     * @param data3 第三个byte
     * @param data4 第四个byte
     * @return int
     */
    public static int byteToInt(byte data1, byte data2, byte data3, byte data4) {
        int num = ((data1 & 0xff) << 24) + ((data2 & 0xff) << 16) + ((data3 & 0xff) << 8) + (data4 & 0xff);
        return num;
    }

    /**
     * 2byte数据转无符号int
     * @param data1 第一个byte
     * @param data2 第二个byte
     * @return int
     */
    public static int byteToInt(byte data1, byte data2) {
        int num = (((data1 & 0xff) << 8) + (data2 & 0xff));
        return num;
    }

    /**
     * 2byte数据转有符号short
     * @param data1 第一个byte
     * @param data2 第二个byte
     * @return short
     */
    public static short byteToShort(byte data1, byte data2) {
        short num = (short) (((data1 & 0xff) << 8) + (data2 & 0xff));
        return num;
    }

    /**
     * 生日转年龄，当前时间戳减去生日的时间戳，然后算有几个365天，然后加1，便是年龄
     * @param birth 生日
     * @return 年龄
     */
    public static int birthToAge(String birth) {
        int age = 0;
        if (birth == null || TextUtils.isEmpty(birth)) {
            birth = "1995/10";
        }
        birth = birth.replace("-", "/");
        long time = DateConvertUtils.convertStringToMill(birth, "yyyy/MM")/1000L;
        age = (int) ((System.currentTimeMillis()/1000L - time)/60/60/24/365 + 1);
        return age;
    }

    /**
     * 将闹钟重复字符串转为16进制数字
     * @param repeat 闹钟重复“0101010”
     * @return int
     */
    public static int repeatStringToInt(String repeat) {
        int loop = 0;
        if (repeat.length() != 7) {
            return loop;
        }
        if ("1".equalsIgnoreCase(repeat.substring(0,1))) {
            loop = loop + 64;
        }
        if ("1".equalsIgnoreCase(repeat.substring(1,2))) {
            loop = loop + 32;
        }
        if ("1".equalsIgnoreCase(repeat.substring(2,3))) {
            loop = loop + 16;
        }
        if ("1".equalsIgnoreCase(repeat.substring(3,4))) {
            loop = loop + 8;
        }
        if ("1".equalsIgnoreCase(repeat.substring(4,5))) {
            loop = loop + 4;
        }
        if ("1".equalsIgnoreCase(repeat.substring(5,6))) {
            loop = loop + 2;
        }
        if ("1".equalsIgnoreCase(repeat.substring(6,7))) {
            loop = loop + 1;
        }
        return loop;
    }

    /**
     * 将闹钟重复转为字符串
     * @param repeat 闹钟重复127
     * @return String
     */
    public static String repeatIntToString(int repeat) {
        String loop = "";
        if (((repeat >> 6) & 0x01) == 1) {
            loop = loop + "1";
        } else {
            loop = loop + "0";
        }
        if (((repeat >> 5) & 0x01) == 1) {
            loop = loop + "1";
        } else {
            loop = loop + "0";
        }
        if (((repeat >> 4) & 0x01) == 1) {
            loop = loop + "1";
        } else {
            loop = loop + "0";
        }
        if (((repeat >> 3) & 0x01) == 1) {
            loop = loop + "1";
        } else {
            loop = loop + "0";
        }
        if (((repeat >> 2) & 0x01) == 1) {
            loop = loop + "1";
        } else {
            loop = loop + "0";
        }
        if (((repeat >> 1) & 0x01) == 1) {
            loop = loop + "1";
        } else {
            loop = loop + "0";
        }
        if ((repeat & 0x01) == 1) {
            loop = loop + "1";
        } else {
            loop = loop + "0";
        }
        return loop;
    }



    /**
     * 保存log文件到log文件夹中
     * @param msgData log数据
     * @param fileName 文件名
     */
    public static void writeLogToSDForLog(byte[] msgData, String fileName) {
        String path = FileUtils.getFolderPath();
        FileUtils.isExist(path);
        path = path + "log/";
        FileUtils.isExist(path);
        File file = getFile(path, fileName);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream stream = new FileOutputStream(file, true);
            stream.write(msgData);
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据文件路径和文件名，得到文件
     * @param path 文件父路径
     * @param filename 文件名
     * @return 文件
     */
    private static File getFile(String path, String filename) {
        File file = new File(path + filename);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            FileInputStream fis = new FileInputStream(file);
            long size = fis.available();
            fis.close();
            /**
             * 当文件大小大于500MByte时，主动删除
             */
            if (size >= 500000000) {
                File f = new File(path + System.currentTimeMillis() + filename);
                file.renameTo(f);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LogUtils.e("fileutils","fileName = " +path + filename );
        }
        return new File(path + filename);
    }



    /**
     * 更加速度转换为颜色
     * @param minSpeed 最小速度
     * @param maxSpeed 最大速度
     * @param speed 当前速度
     * @return 颜色
     */
    private static int speedToColor(int minSpeed, int maxSpeed, int speed) {
        if (maxSpeed > minSpeed) {
            int avgSpeed = (maxSpeed + minSpeed) / 2;
            if (speed > avgSpeed) {
                float progress = (speed - avgSpeed) * 100 / (maxSpeed - avgSpeed)*1.0f;
                int color = Color.argb(170, 255,  (int) (255 - 255 * progress), 0);
                return color;
            } else if (speed == avgSpeed) {
                return 0xAAffff00;
            } else {
                float progress = (speed - avgSpeed) * 100 / (avgSpeed - minSpeed)*1.0f;
                int color = Color.argb(170, (int) (255 * progress),  255,0);
                return color;
            }
        }
        return 0xAAff0000;
    }

}
